package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();
        List<Long> productIds = createOrderContext.getBuyProductIds();
        if (CollectionUtils.isEmpty(productIds)) {
//            //用增强for循环获取productIds
//            for (CartProductDto cartProductDto : dtoList) {
//                productIds.add(cartProductDto.getProductId());
//            }

            //用stream流和lambda表达式获取productIds
            productIds = dtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());

        }
        //排序
        productIds.sort(Long::compareTo);
        //锁定库存
        List<Stock> stocksList = stockMapper.findStocksForUpdate(productIds);

        if (CollectionUtils.isEmpty(stocksList)) {
            throw new BizException(OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(),OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }
        if (stocksList.size() != productIds.size()) {
            throw new BizException(OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getCode(),OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }

        //扣减库存
        for (CartProductDto cartProductDto : dtoList) {
            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();


            Stock stock1 = stockMapper.selectStock(productId);
            Integer restrictCount = stock1.getRestrictCount();
            if (restrictCount < productNum) {
                throw new BizException("购买数量不能超出限购数量！");
            }

            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);

            stockMapper.updateStock(stock);

        }


        return true;
    }
}